// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  // 给定 DYNAMIC_CURRENT_ENV 常量：接下来的 API 调用都将请求到与该云函数当前所在环境相同的环境
  env: cloud.DYNAMIC_CURRENT_ENV
})

// 云函数入口函数
exports.main = async (event, context) => {
  const DB1 = cloud.database().collection('wait_right');
  const DB2 = cloud.database().collection('login_coupon');
  if (event.type == 'addwait') {
    //记录数据库
    let add_list = await DB1.add({ data: event.data_list });
    //删除优惠卷
    let delect_coupon = null;
    if (event.coupon_id != '') {
      delect_coupon = await DB2.doc(event.coupon_id).remove();
    };
    return { add_list, delect_coupon };
  } else if (event.type == 'get_wait') {
    return await DB1.where({ _openid: event.openid }).get();
  } else if (event.type == 'del_wait') {
    return await DB1.doc(event.id).remove();
  } else if (event.type == 'get_phone') {
    return await cloud.getOpenData({ list: [event.cloudID] })
  } else if (event.type == 'get_code') {
    //查询收货码
    return await cloud.database().collection('login_inf').where({ login_openid: event.openid }).get();
  } else if (event.type == 'up_code') {
    //查询是否有该码
    let login_inf = await cloud.database().collection('login_inf').where({ login_openid: event.openid }).get();
    if (login_inf.data.length == 0) {
      //添加该码
      let add_inf = await cloud.database().collection('login_inf').add({ data: event.datas });
      return { login_inf, add_inf, code: 200 }
    } else {
      return { login_inf, add_inf: '', code: 400 }
    }

  }
}